package git.soulbgm.controller;

import git.soulbgm.job.JobOperateAPI;
import git.soulbgm.job.JobService;
import git.soulbgm.mapper.JobInfoMapper;
import git.soulbgm.pojo.JobInfo;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 定时任务的控制器
 *
 * @author SoulBGM
 * @date 2020/11/18
 */
@RestController
public class JobController {

    @Resource
    private JobInfoMapper jobInfoMapper;

    @Autowired
    private JobService jobService;

    @Autowired
    private JobOperateAPI jobOperateAPI;

    @GetMapping("getAll")
    public List<JobInfo> getAll() {
        return jobInfoMapper.selectAll();
    }

    @PostMapping("update")
    public String update(@RequestBody JobInfo jobInfo) {
        jobService.initJob(jobInfo);
        jobInfoMapper.updateByPrimaryKeySelective(jobInfo);
        return "success";
    }

    @PostMapping("add")
    public String add(@RequestBody JobInfo jobInfo) {
        jobService.initJob(jobInfo);
        jobInfoMapper.insertSelective(jobInfo);
        return "success";
    }

    @PostMapping("disable")
    public String disable(String jobName) {
        jobOperateAPI.disable(jobName, null);
        return "success";
    }

    @PostMapping("enable")
    public String enable(String jobName) {
        jobOperateAPI.enable(jobName, null);
        return "success";
    }

    @SneakyThrows
    @PostMapping("del")
    public String del(String jobNames) {
        String[] split = jobNames.split(",");
        for (String jobName : split) {
            jobOperateAPI.disable(jobName, null);
        }
        Thread.sleep(2500);
        for (String jobName : split) {
            jobOperateAPI.removeAll(jobName);
        }
        List<String> jobNameList = new ArrayList<>(split.length);
        Collections.addAll(jobNameList, split);
        Example example = new Example(JobInfo.class);
        example.and().andIn("jobName", jobNameList);
        jobInfoMapper.deleteByExample(example);
        return "success";
    }

}
